package org.csu.mypetstore.web.servlets;

import java.io.IOException;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.service.CatalogService;

public class UpdateCartQuantitiesServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private String workingItemId;
    private Cart cart;

    public UpdateCartQuantitiesServlet() {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.workingItemId = request.getParameter("workingItemId");
        new CatalogService();
        HttpSession session = request.getSession();
        this.cart = (Cart)session.getAttribute("cart");
        Iterator cartItemIterator = this.cart.getAllCartItems();

        while(cartItemIterator.hasNext()) {
            CartItem cartItem = (CartItem)cartItemIterator.next();
            String itemId = cartItem.getItem().getItemId();

            try {
                int quantity = Integer.parseInt(request.getParameter(itemId));
                this.cart.setQuantityByItemId(itemId, quantity);
                if (quantity < 1) {
                    cartItemIterator.remove();
                }
            } catch (Exception var9) {
                var9.printStackTrace();
            }
        }

        session.setAttribute("cart", this.cart);
        request.getRequestDispatcher(VIEW_CART).forward(request, response);
    }
}
